package com.qf.service.impl;

/*
 *  @author Administrator
 *  @version V1.0
 *  @Project smartdeviceplatgorm
 *  @Package com.qf.service.impl
 *  @Description
 *  @Date2022/3/22 0022 16:31
 */

import com.github.pagehelper.PageInfo;
import com.qf.bean.SysCategory;
import com.qf.bean.SysDevice;
import com.qf.bean.SysScene;
import com.qf.bean.SysUserInfo;
import com.qf.cache.CategoryCache;
import com.qf.cache.SceneCache;
import com.qf.enums.EmptyType;
import com.qf.exception.AddDataException;
import com.qf.exception.QueryDataException;
import com.qf.mapper.SysCategoryMapper;
import com.qf.mapper.SysDeviceMapper;
import com.qf.service.SysDeviceService;
import com.qf.utils.ResultCode;
import com.qf.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysDeviceServiceImpl implements SysDeviceService {
    private SysDeviceMapper sysDeviceMapper;
    private SysCategoryMapper sysCategoryMapper;
    private SceneCache sceneCache;
    private CategoryCache categoryCache;
    @Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }

    @Autowired
    public void setSysCategoryMapper(SysCategoryMapper sysCategoryMapper) {
        this.sysCategoryMapper = sysCategoryMapper;
    }

    @Autowired
    public void setSysDeviceMapper(SysDeviceMapper sysDeviceMapper) {
        this.sysDeviceMapper = sysDeviceMapper;
    }

    @Override
    public void addSysDevice(SysDevice sysDevice) {
        //检查当前是不是登录了用户,如何判断用户登录了, 所以一定有个地方保存了登录的用户(数据到底保存在什么地方是我们决定的),我们登录完成后放到session了
        //那我们只需要从session中获取
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        Assert.notNull(loginUser, () -> {
            throw new AddDataException("未登录", ResultCode.LOGIN_NOT);
        });
//        String deviceId = UUID.randomUUID().toString().replace("-","");
//        sysDevice.setDeviceId(deviceId);
        if (sysDevice.getSceneId() == null || sysDevice.getSceneId() <= 0) {
            sysDevice.setSceneId(-1);
        }else {
            //传递了场景id,但是不是-1,需要检查这个场景的id是不是属于当前用户
            //我们有场景的缓存,可以直接从缓存中查询这个场景的数据
            SysScene sysScene = sceneCache.get(sysDevice.getSceneId());
            //这个场景可能不存在,也可能不属于当前用户, 但是不管什么情况,只要不符合,我们就提示场景不存在
            Assert.isTrue(sysScene != null && sysScene.getCreateBy() == loginUser.getUId(),()->{
                throw new AddDataException("场景不存在", ResultCode.SCENE_NOT_EXIST);
            });
        }
        SysCategory sysCategory = sysCategoryMapper.findById(sysDevice.getCategyId());
        Assert.notNull(sysCategory,()->{
            throw new AddDataException("分类不存在",ResultCode.SYSCATEGORY_EXIST);
        });
        Assert.isTrue(sysCategory.getCreateBy().equals(loginUser.getUsername()),()->{
            throw new AddDataException("这个分类不是当前用户的", ResultCode.SYSCATEGORY_EXIST);
        });
        sysDevice.setBindUserId(loginUser.getUId());
        Assert.isTrue(sysDevice.getBindUserId().equals(loginUser.getUId()),()->{
            throw new AddDataException("绑定用户不匹配", ResultCode.BINDUSER_NOMATCH);
        });
        sysDevice.setBindTime(new Date());
        sysDevice.setIsOnline(2);
        //检查是不是传数据了
        Assert.isTrue(!sysDevice.isEmpty(EmptyType.ADD), () -> {
            throw new AddDataException("数据没有填写完整", ResultCode.DATA_NULL);
        });
        SysDevice device = sysDeviceMapper.findById(sysDevice.getDeviceId());
        Assert.isNull(device,()->{
            throw new AddDataException("设备已经存在", ResultCode.DEVICE_EXIST);
        });

        sysDeviceMapper.addSysDevice(sysDevice);
    }

    @Override
    public PageInfo<SysDevice> findBySelf(Integer page,Integer limit) {
        SysUserInfo userInfo = SecurityUtils.getLoginUser();
        Assert.notNull(userInfo, () -> {
            throw new AddDataException("未登陆", ResultCode.LOGIN_NOT);
        });
//        PageHelper.startPage(page, limit);
        List<SysDevice> bySelf = sysDeviceMapper.findBySelf(userInfo.getUId());
        List<SysDevice> collect = bySelf.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        //当前设备关联的分类数据没有查询
        collect.forEach(sysDevice1 -> {
            Integer categyId = sysDevice1.getCategyId();//当前设备关联的分类id
            //我们有一个分类缓存,分类缓存中提供了一个根据id查询分类的功能
            SysCategory category = categoryCache.getWithDelete(categyId);
            sysDevice1.setCategory(category);//给当前的设备设置分类
        });
        PageInfo<SysDevice> pageInfo = new PageInfo<>(collect);
        pageInfo.setTotal(bySelf.size());
        pageInfo.setPageNum(page);
        return pageInfo;
    }

    @Override
    public SysDevice findById(String deviceId) {
        //判断用户有没有登录
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        //我们要求必须登录
        Assert.notNull(loginUser,()->{
            throw new QueryDataException("未登陆", ResultCode.LOGIN_NOT);
        });

        SysDevice sysDevice = sysDeviceMapper.findById(deviceId);

        Assert.isTrue(sysDevice!=null&&loginUser.getUId()==sysDevice.getSceneId(),()->{
            throw new QueryDataException("设备不存在", ResultCode.DEVICE_NOT_EXIST);
        });
        return sysDevice;
    }

    @Override
    public int updateDeviceById(SysDevice sysDevice) {
        int result = sysDeviceMapper.updateDeviceById(sysDevice);
        return result;
    }
}
